package edu.cuit.avatar;

import java.io.*;

/**
 * ObjectInputStream / ObjectOutputStream
 *
 * 并不是每个对象都可以写入到输出流，可以写入到输出流中的对象称为"可序列化的".因为可序列化的对象是java.io.Serializable接口的实例。
 * 所以，可序列化对象的类必须实现Serializable接口.
 *
 * Serializable接口是一个标记接口。实现该接口可以启动java的序列化机制，自动完成存储对象的过程
 *
 * 序列化:将对象转为字节序列。
 * 反序列化:将字节序列转为对象
 *
 * 序列化的目的: 持久化;网络间数据传输
 *
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/12 10:49
 */
public class ObjectStream {
    public static void save(Student student){
        try(var out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("student.dat")))){
            out.writeObject(student);
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        var student = new Student("Peppa", 5, "跳泥坑", "Female");
//        save(student);

//        var peppa = read();
//        System.out.println(peppa.getName());
//        System.out.println(peppa);
//
//        System.out.println("nextId:" + Student.getNextId());

        saveArray();
    }

    public static Student read(){
        try(var input = new ObjectInputStream(new BufferedInputStream(new FileInputStream("student.dat")))){
            return (Student)input.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //序列化数组,要求该数组是一个可序列化(数组中的每个元素都是可序列化)
    public static void saveArray(){
        Object[] students = {new Student("Peppa", 5, "跳泥坑", "Female"),
                             new Student("Suzy", 5, "~~", "Female")};
        try(var out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("array.dat")))){
            out.writeObject(students);
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}
